﻿using System;
using System.Collections.Generic;
using System.Linq;
using Marmat.Foundation;
using Marmat.FrameWork;

namespace Marmat.Template.WinForm
{

    /// <summary>
    /// 菜单构建器的默认实现。
    /// </summary>
    public abstract class MenuItemBuilder : IMenuItemBuilder
    {
        private readonly List<IMenu> eventCollection = new List<IMenu>();

        /// <summary>
        /// 构建菜单项。
        /// </summary>
        /// <returns></returns>
        public abstract void Builder(List<IMenu> menus);

        /// <summary>
        /// 菜单项的点击事件。
        /// </summary>
        /// <param name="menu">点击的菜单项。</param>
        public abstract void ItemClick(IMenu menu);

        void IMenuItemBuilder.Builder(List<IMenu> menus)
        {
            this.Builder(menus);
            foreach (var menu in menus)
            {
                if (menu.Argument is not null || !menus.Exists(item => item.Parent == menu.Name))
                    eventCollection.Add(menu);
            }
        }

        void IMenuItemBuilder.ItemClick(IMenu menu)
        {
            if (this.eventCollection.Contains(menu))
            {
                IMainForm mainForm = SystemCommand.GetService<IMainForm>();
                if (mainForm.ContainsForm(menu.Name))
                    mainForm.SelectedFormName = menu.Name;
                else
                    this.ItemClick(menu);
            }
        }
    }
}
